package com.wc.alorithm_blue_bridge._数据结构.单调队列.Q1207;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayDeque;

/**
 * @Author congge
 * @Date 2023/11/4 20:47
 * MAX最值差
 * https://www.lanqiao.cn/problems/1207/learning/?page=2&first_category_id=1&sort=students_count&second_category_id=8
 */
public class Main {
    public static void main(String[] args) {
        Input sc = new Input();
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] array = new int[n];
        MyQueue maxQueue = new MyQueue();
        MyQueue minQueue = new MyQueue(false);
        for (int i = 0; i < n; i++) {
            array[i] = sc.nextInt();
        }
        for (int i = 0; i < k && i < n; i++) {
            maxQueue.push(array[i]);
            minQueue.push(array[i]);
        }
        int ans = maxQueue.front() - minQueue.front();
        for (int i = k; i < n; i++) {
            maxQueue.pop(array[i - k]);
            maxQueue.push(array[i]);
            minQueue.pop(array[i - k]);
            minQueue.push(array[i]);
            ans = Math.max(ans, maxQueue.front() - minQueue.front());
        }
        System.out.println(ans);
    }

    static class MyQueue {
        private final ArrayDeque<Integer> queue;
        /**
         * 判断是否为最大单调栈
         */
        private final boolean flg;

        public MyQueue() {
            this(true);
        }

        public MyQueue(boolean flg) {
            this.flg = flg;
            queue = new ArrayDeque<>();
        }

        public void push(int val) {
            if (flg) {
                while (!queue.isEmpty() && val > queue.getLast()) {
                    queue.removeLast();
                }
            } else {
                while (!queue.isEmpty() && val < queue.getLast()) {
                    queue.removeLast();
                }
            }
            queue.addLast(val);
        }

        public void pop(int val) {
            if (!queue.isEmpty() && queue.getFirst() == val) {
                queue.removeFirst();
            }
        }

        public int front() {
            return queue.getFirst();
        }
    }

    static class Input {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

        public int nextInt() {
            try {
                in.nextToken();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (int) in.nval;
        }
    }
}
